<script>
import requestApi from './utils/request';
import Toast from 'wxcomponents/vant/toast/toast';
import myevent from './utils/event'
let throttleTimer = null

export default {
  onLaunch: function () {
    const that = this
    const token = uni.getStorageSync('token');
    console.log(666666666666666666666);
    console.log(token);
    // #ifdef APP-PLUS
    if(!token) {
      // app 端没有token 要自己登录
      uni.redirectTo({
        url: '/pages/appLogin/appLogin'
      })
    } else {

    }
    // #endif


    if (token) {
      this.globalData.token = token
      this.handleGetUserInfo()
    } else {
      // #ifdef MP-WEIXIN
      this.handleLogin()
      // #endif
    }

    uni.getSystemInfo({
      success: function (res) {
        // 有横杆的导航栏高度大于20
        if (res.safeArea.top > 20) {
          that.globalData.isIphoneX = true;
        }
      }
    });

    /*wx.setEnable1v1Chat({
      enable: true,
      success(res) {
        console.log(res);
        console.log('777777777');
      },
      fail(res) {
        console.log(res);
        console.log('777777777err');
      },
    })*/

  },
  onShow: function () {
    console.log('App Show')
  },
  onHide: function () {
    console.log('App Hide')
  },
  globalData: {
    curTabIndex: 2,
    isIphoneX: false,
    event: new myevent(),
    token: '',
    a: 1,
    ftp: 'https://tdt.qwtjt.com',
    uploadTrajectoryTime: null,
    latitude: '',
    longitude: '',
    mapKey: '44KBZ-RQVLI-2VUGZ-UIRZW-P3V62-TMFWM',


    userInfo: {
      id: '',
      avatar: '',
      nickname: '',
      mobile: '',
      auth_type: '',
      express_type: '',
    },

    selectExpressManInfo: false
  },
  methods: {
    request(data, path) {
      data = data || {}
      data['token'] = this.globalData.token
      return requestApi.request.bind(requestApi)(data, path)
    },
    upload(tempFilePath, data, path) {
      data = data || {}
      data['token'] = this.globalData.token
      return requestApi.upload.bind(requestApi)(tempFilePath, data, path)
    },
    handleLogin() {
      const that = this

      uni.login({
        provider: 'weixin', //使用微信登录
        success: function (res) {
          const {
            code
          } = res

          that.request({
            code
          }, '/api/logistics/user/auth_login').then((res) => {
            const {
              code,
              msg,
              data
            } = res

            if (code === 1) {
              const {
                id,
                avatar,
                nickname,
                token,
              } = data

              that.globalData.userInfo.id = id
              that.globalData.userInfo.avatar = that.globalData.ftp + avatar
              that.globalData.userInfo.nickname = nickname
              that.globalData.token = token
              uni.setStorageSync('token', token);
              that.handleGetUserInfo()
            } else {
              Toast(msg)
            }
          })
        },
        fail(res) {
          console.log(res);
        }
      });
    },
    handleGetUserInfo() {
      this.request({}, '/api/logistics/user/user_info').then((res) => {
        const {
          code,
          data,
          msg
        } = res

        if (code === 1) {
          const {
            id,
            avatar,
            nickname,
            mobile,
            auth_type,
            express_type
          } = data

          this.globalData.userInfo.id = id
          this.globalData.userInfo.avatar = this.globalData.ftp + avatar
          this.globalData.userInfo.nickname = nickname
          this.globalData.userInfo.mobile = mobile
          this.globalData.userInfo.auth_type = auth_type
          this.globalData.userInfo.express_type = express_type
          if (parseInt(express_type) === 1) {
            // 上传轨迹
            this.handleUploadTrajectory()
          }
        }
      })
    },
    getQueryStringByObject(obj) {
      const queryKeys = Object.keys(obj)
      let query = `?`

      queryKeys.forEach((res) => {
        query += `${res}=${obj[res]}&`
      })

      return query
    },
    pageJump(tabIndex) {
      this.globalData.curTabIndex = tabIndex

      if (tabIndex === 0) {
        uni.redirectTo({
          url: '/pages/kdOrder/home'
        })
      } else if (tabIndex === 1) {
        uni.redirectTo({
          url: '/pages/kdOrder/grabbing'
        })
      } else if (tabIndex === 2) {
        uni.redirectTo({
          url: '/pages/rider/center'
        })
      }
    },
    handleUploadTrajectory() {
      const that = this

      uni.startLocationUpdateBackground({
        success(res) {
          console.log(res);
          console.log(11111);
        },
        fail(res) {
          console.log(res);
          console.log(222222);


          wx.getSetting({
            success: function (res) {
              var status = res.authSetting;
              console.log(status)
              if (!status["scope.userLocationBackground"]) {
                wx.showModal({
                  title: "您的身份是骑手，位置信息请选择使用小程序时和离开后允许",
                  content: "需要持续获取您的地理位置，请确认授权，否则订单可能会接收失败",
                  success: function (tip) {
                    if (tip.confirm) {
                      wx.openSetting({
                        success: function (data) {
                          console.log(data);
                          if (data.authSetting["scope.userLocationBackground"] === true) {
                            that.handleUploadTrajectory()
                          }
                        }
                      });
                    } else {
                      //console.log('用户拒绝打开设置界面')
                    }
                  }
                });
              }
            }
          })

        },
        complete(res) {
          console.log(res);
          console.log(333333);
        }
      })
      uni.onLocationChange((res) => {
        console.log(44444444);
        console.log(res);
        const {
          latitude,
          longitude
        } = res

        that.globalData.latitude = latitude
        that.globalData.longitude = longitude

        if (throttleTimer) {
          // 节流
          return
        }
        that.handleUploadTrajectoryApi({
          latitude,
          longitude
        })

        throttleTimer = setTimeout(() => {
          clearTimeout(throttleTimer)
        }, 600)
      })
    },


    handleUploadTrajectoryApi(dot) {
      const {
        latitude,
        longitude
      } = dot

      this.request({
        lat: latitude,
        // lat: 28.191128,
        lnt: longitude
        // lnt: 112.892207
      }, '/api/logistics/express/express_track').then((res) => {
        const {
          code,
          msg,
          data
        } = res
        console.log(res);
        if (code === 1) {}
      })
    }

  },
}
</script>

<style lang="scss">
/*每个页面公共css */
@import "/wxcomponents/vant/common/index.wxss";

.kd-tabBar-wrap {
  display: flex;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  background-color: #fff;
  border-top: 1rpx solid #F3F3F5;
  box-sizing: border-box;
  .tab-wrap {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .tab-image {
      width: 50rpx;
      height: 50rpx;
    }
    .tab-name {
      font-size: 22rpx;
      color: #DBDBDB;
    }
  }
  .cur-tab {
    .tab-name {
      color: #4CC1EE;
    }
  }
}


.selected-text {
  .uni-list-item__extra-text {
    color: #000;
  }
}

</style>
